package com.ljy.jymail.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.ljy.common.exception.NoStockException;
import com.ljy.common.to.mq.OrderTo;
import com.ljy.common.to.mq.StockDetailTo;
import com.ljy.common.to.mq.StockLockedTo;
import com.ljy.common.utils.R;
import com.ljy.jymail.ware.entity.WareOrderTaskDetailEntity;
import com.ljy.jymail.ware.entity.WareOrderTaskEntity;
import com.ljy.jymail.ware.feign.OrderFeignService;
import com.ljy.jymail.ware.feign.ProductFeignService;
import com.ljy.jymail.ware.service.WareOrderTaskDetailService;
import com.ljy.jymail.ware.service.WareOrderTaskService;
import com.ljy.jymail.ware.vo.OrderItemVo;
import com.ljy.jymail.ware.vo.OrderVo;
import com.ljy.jymail.ware.vo.SkuHasStockVo;
import com.ljy.jymail.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.common.utils.PageUtils;
import com.ljy.common.utils.Query;

import com.ljy.jymail.ware.dao.WareSkuDao;
import com.ljy.jymail.ware.entity.WareSkuEntity;
import com.ljy.jymail.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
@RabbitListener(queues = "stock.release.stock.queue")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;





    //解锁库存
    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        detailEntity.setLockStatus(2);//变为已解锁
        wareOrderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }



    /*入库*/
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判读如果没有这个库存记录新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(
                new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败整个事务无需回滚
            //1、自己catch异常
            try{
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            //添加库存信息
            wareSkuDao.insert(wareSkuEntity);
        } else {
            //修改库存信息
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }



    /*检查每一个商品的库存*/
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(item -> {
            Long count = this.baseMapper.getSkuStock(item);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(item);
            skuHasStockVo.setHasStock(count == null?false:count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    /*
    * @TODO 为某个订单锁定库存
    * @author ljy
    * @time 2022-02-10 11:05:05
    * @method orderLockStock
    * @param param
    * @return java.util.List<com.ljy.jymail.ware.vo.LockStockResult>
    *
    * 库存解锁的场景
    * 1、下单成功。订单过期没有支付被系统自动取消、被用户手动取消。都要解锁库存
    * 2、远程方法出现错误进行回滚
    *
    *
    */
    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //TODO 按照下单的收货地址，找到一个就近仓库，锁定库存

        /*
        * 保存库存工作单详情---追溯工作单锁定数据，方便出现问题后的人为追溯
        * */
        System.out.println(vo.getOrderSn()+"  :"+vo.getLocks().get(0).getSkuId());
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        System.out.println("taskEntity:---------------------"+taskEntity);
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);
//        System.out.println("这里1");
        //1、找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

//        Boolean allLock = true;
//        System.out.println("这里2");
        //2、锁定库存
        for (SkuWareHasStock hasStock:collect){
            boolean skuStocked = false;//默认没被锁定住
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0){
//                System.out.println("wareIds"+wareIds);

                //没有任何仓库有这个商品库存
                throw new NoStockException(skuId);
            }
            //如果每一个商品都锁成功，将当前商品保存了几件的工作单详情记录发送给mq
            //如果锁定失败。前面保存的工作信息单就回滚了。
            //那么就从rabbitMq发送的消息中取出信息，进行手动的还原操作
            // 1-2-3 2-1-2 3-1-1(x)
            for (Long wareId:wareIds){
                //没有问题：锁定商品，仓库，件数
                //成功返回1 ， 未成功返回0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count == 1){
                    //锁定成功,rabbitMq发送消息
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null,skuId,"",hasStock.getNum(),taskEntity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(detailEntity);
                    //rabbit发送消息告诉服务器锁定成功
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity,stockDetailTo);
                    //不能只发Id，防止回滚之后找不到数据
                    stockLockedTo.setId(taskEntity.getId());
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    //TODO:触发解锁逻辑
                    skuStocked = true;
                    break;
                }else {
                    //当前仓库锁失败了，去下一个仓库
                }
            }
//            System.out.println("这里3");
            if (skuStocked == false){
                //所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

//        System.out.println("这里4");
        //走到这里说明全部锁定成功
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {

        StockDetailTo detail = to.getDetail();//库存工作单详细信息
        Long detailId = detail.getId();

        //解锁 由于锁库存失败导致回滚，此时库存工作单的数据也会回滚 -所以先查询数据库，查看订单是否有锁定库存信息
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId != null){
            //有 证明库存锁定成功，说明其他信息失败，需要进行解锁
            //解锁 订单情况 ：
            //         1、 没有订单，则必须解锁
            //         2、 有订单，不是解锁库存，判断订单状态
            //                      3、已取消 -- 解锁库存   没取消  --- 不能解锁
            Long id = to.getId();//库存工作单Id
            //根据订单号去订单系统查询
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            //根据订单号，查询订单状态
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            if (orderStatus.getCode()==0){
                //订单数据返回成功
                OrderVo data = orderStatus.getData(new TypeReference<OrderVo>() {});
                if (data==null||data.getStatus()==4){//4-订单取消 订单不存在的情况

                    //如果当前的锁定状态不是已解锁才可以解锁
                    if(byId.getLockStatus()==1){//1-已锁定且未解锁
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                    //手动通知接收到消息
                }
            }else {
                //远程服务调用失败，拒绝消息：让消息重新发送队列，让其他继续使用消息
                throw new RuntimeException("远程服务失败");
            }

        } else {
            //没有 由于锁库存失败导致回滚，导致库存工作单的数据回滚 此情况无需解锁，其自动回滚

        }
    }

    /*
    * 订单关闭发送消息，解锁库存
    * 防止订单服务卡顿，导致订单状态消息无法发送，库存到期后查询状态判断后什么都不做
    * 导致卡顿的订单的库存永久无法解锁
    * */
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {

        String orderSn = to.getOrderSn();
        //查询最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        //按照工作单，找到所有没有解锁的库存、进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id)
                .eq("lock_status", 1));
        //Long skuId,Long wareId,Integer num,Long taskDetailId
        for (WareOrderTaskDetailEntity entity:list){
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }


    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }

}